﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Crm.Sdk;

namespace Crm.Plugins.DuplicateChecker.Data{
    /// <summary>
    /// 
    /// </summary>
    internal sealed class TargetEntityRepository : CrmRepository{
        public TargetEntityRepository(ICrmService crmService) : base(crmService){}

        private static string getFetchXml(string entityName, string keyAttribute, int entityId){
            return
                string.Format(
                    @"<fetch><entity name='{0}'><attribute name='{1}' /><filter><condition attribute='{1}' operator='eq' value='{2}' /></filter></entity></fetch>",
                    entityName, keyAttribute, entityId);
        }

        /// <summary>
        /// Searches for the number of entity instances that exist for the given Id.
        /// </summary>
        /// <returns>Count of entity instances.</returns>
        public int GetCount(string entityName, string keyAttribute, int entityId){
            string fetchXml = getFetchXml(entityName, keyAttribute, entityId);
            IEnumerable<string> existingWorkItems = getExistingEntities(fetchXml, keyAttribute);
            return existingWorkItems.Count();
        }

        private IEnumerable<string> getExistingEntities(string fetchXml, string keyAttribute){
            string fetchXmlResponse = _crmService.Fetch(fetchXml);
            XDocument xdocument = XDocument.Parse(fetchXmlResponse);
            IEnumerable<string> exististingEntityIds = from item in xdocument.Descendants(keyAttribute) select item.Value;
            return exististingEntityIds;
        }
    }
}